package com.qyhl.module_home.main;

import com.orhanobut.hawk.Hawk;
import com.qyhl.webtv.basiclib.utils.DateUtils;
import com.qyhl.webtv.basiclib.utils.StringUtils;
import com.qyhl.webtv.commonlib.common.CommonUtils;
import com.qyhl.webtv.commonlib.constant.AppConfigConstant;
import com.qyhl.webtv.commonlib.entity.config.AppConfigBean;
import com.qyhl.webtv.commonlib.entity.home.TokenBean;
import com.qyhl.webtv.commonlib.entity.news.NewsStyleBean;
import com.qyhl.webtv.commonlib.entity.user.UserInfoBean;
import com.qyhl.webtv.commonlib.utils.eventbus.BusFactory;
import com.qyhl.webtv.commonlib.utils.eventbus.Event;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by PVer on 2017/10/3.
 */

public class MainPresenter implements MainContract.MainPresenter {

    private MainActivity mView;
    private MainModel mModel;

    MainPresenter(MainActivity mainView) {
        this.mView = mainView;
        this.mModel = new MainModel(this);
    }

    @Override
    public void configHttpError() {
        if (Hawk.contains("config")) {
            AppConfigBean bean = Hawk.get("config");
            setConfig(bean);
        } else {
            mView.regainConfig();//重新获取配置信息
        }
    }

    /**
     * 配置信息设置
     *
     * @param bean
     */
    @Override
    public void setConfig(AppConfigBean bean) {
        if (bean == null && (CommonUtils.getInstance().getSite() == 127 || CommonUtils.getInstance().getSite() == 140)) {
            mView.successConfig(null);
            return;
        }

        if (CommonUtils.getInstance().getSite() == 148) {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.HAS_HISTORY, true);
        } else {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.HAS_HISTORY, false);
        }

        if (CommonUtils.getInstance().getHasHistory()) {
            //判断历史阅读是否已超过保存期限
            if (Hawk.contains("readHistory")) {
                Map<String, String> map = Hawk.get("readHistory");
                Map<String, String> readHistory = new HashMap<>();
                for (Map.Entry<String, String> vo : map.entrySet()) {
                    String historyTime = (String) vo.getValue();
                    String newsId = (String) vo.getKey();
                    if (DateUtils.isDuringHistoryDate(historyTime)) {
                        readHistory.put(newsId, historyTime);
                    }
                }
                CommonUtils.getInstance().putConfigData(AppConfigConstant.READ_HISTORY, readHistory);
                Hawk.put("readHistory", readHistory);
            }
        }

        analysisStyle(bean.getNewsStyle());//解析出新闻列表的样式

        analysisAdv(bean.getAdvSwitch());
//        analysisAdv("1,0,0,0");
        //解析出乡镇,政务,专题的ID
        analysisId(bean.getRuralSection());

        CommonUtils.getInstance().setLuckDrawUrl(bean.getReceiptUrl() + "/");
        CommonUtils.getInstance().setSiteName(bean.getTagName());


        //保存临时变量

        //app是否置灰
        Hawk.put("homeGray", bean.getHomeGray());

        //链接是否可以分享
        CommonUtils.getInstance().putConfigData(AppConfigConstant.LINK_URL_SHARE, bean.getLinkUrlShare());


        //cms新闻审核模式
        CommonUtils.getInstance().putConfigData(AppConfigConstant.COMMENT_RULE, bean.getCommentRule());

        if (StringUtils.isNotEmpty(bean.getIntegralSwitch())) {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.INTEGRAL_SWITCH, bean.getIntegralSwitch());
        }
        CommonUtils.getInstance().putConfigData(AppConfigConstant.HTTP_CODE_URL, bean.getCmsUrl());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.SECTION_BANNER_NUM, bean.getSectionBannerNum());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.SECTION_BANNER_NUM, bean.getSectionBannerNum());
//        app.getConfData().put("sectionId", bean.getSections());
        //App配色类型
        CommonUtils.getInstance().putConfigData(AppConfigConstant.APP_COLOR, bean.getAppColor());
        //显示最小评论数量
        CommonUtils.getInstance().putConfigData(AppConfigConstant.COMMENT_NUM, bean.getMinComment());
        //首页banner显示的最大数量
        CommonUtils.getInstance().putConfigData(AppConfigConstant.BANNER_NUM, bean.getBannerNum());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.APP_NAME, bean.getAppName());
        //分享地址
        CommonUtils.getInstance().putConfigData(AppConfigConstant.ADVURL, bean.getAdvUrl());
        //显示最小点赞数
        CommonUtils.getInstance().putConfigData(AppConfigConstant.MIN_PLAY, bean.getMinPlay());
        CommonUtils.getInstance().putConfigData(AppConfigConstant.MINLIKE, bean.getMinLike());
        String ip = bean.getActShareUrl() + "/" + bean.getTagName() + "/";
        CommonUtils.getInstance().putConfigData(AppConfigConstant.IP, ip);
        CommonUtils.getInstance().putConfigData(AppConfigConstant.IP, ip + "activity/sharehtml/");
//        app.getConfData().put("shareUrl", ip + "activity/sharehtml/");
        CommonUtils.getInstance().putConfigData(AppConfigConstant.TOPMESSAGE, bean.getTopMessage());
        mView.successConfig(bean);
    }

    @Override
    public void getConfig() {
        mModel.getConfig();//获取配置信息
    }

    @Override
    public void compareToken() {
        if (Hawk.contains("token")) {
            String token = Hawk.get("token");
            CommonUtils.getInstance().putConfigData(AppConfigConstant.LOGIN_TOKEN, token);
            mModel.compareToken(token);
        }
    }

    @Override
    public void compareSuccess(TokenBean tokenBean) {
        if (Hawk.contains("login")) {
            UserInfoBean bean = Hawk.get("login");
            if (StringUtils.isEmpty(bean.getNickName())) {
                CommonUtils.getInstance().putConfigData(AppConfigConstant.NICK_NAME, bean.getUsername().replace(bean.getUsername().substring(3, 7), "****"));
            } else {
                CommonUtils.getInstance().putConfigData(AppConfigConstant.NICK_NAME, bean.getNickName());
            }
            CommonUtils.getInstance().putConfigData(AppConfigConstant.USER_NAME, bean.getUsername());
            CommonUtils.getInstance().putConfigData(AppConfigConstant.HEAD_ICON, bean.getLogo());
            CommonUtils.getInstance().putConfigData(AppConfigConstant.CODE, bean.getCode());
            CommonUtils.getInstance().putConfigData(AppConfigConstant.INVITE_CODE, bean.getInviteCode());
            String sex;
            if (StringUtils.isEmpty(bean.getSex())) {
                sex = "C";
            } else {
                sex = bean.getSex();
            }
            //性别，保密为C
            CommonUtils.getInstance().putConfigData(AppConfigConstant.SEX, sex);
            CommonUtils.getInstance().putConfigData(AppConfigConstant.EMAIL, bean.getEmail());
            CommonUtils.getInstance().putConfigData(AppConfigConstant.PHONE_NUM, bean.getTelphone());
        }
        BusFactory.getBus().post(new Event.LoginMessage(true));
    }

    @Override
    public void compareError() {
        if (Hawk.contains("token")) {
            Hawk.delete("token");
        }

        if (Hawk.contains("login")) {
            Hawk.delete("login");
        }
        CommonUtils.getInstance().putConfigData(AppConfigConstant.NICK_NAME, "");
        CommonUtils.getInstance().putConfigData(AppConfigConstant.LOGIN_TOKEN, "");
        CommonUtils.getInstance().putConfigData(AppConfigConstant.USER_NAME, "");
        BusFactory.getBus().post(new Event.LoginMessage(false));
    }

    /**
     * 解析出乡镇,政务,专题的ID
     *
     * @param str
     */
    private void analysisId(String str) {
        if (StringUtils.isNotEmpty(str)) {
            int maxSplit = 3;
            String[] sourceStrArray = str.split(",", maxSplit);
            for (int i = 0; i < sourceStrArray.length; i++) {
                if (i == 0) {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.COUNTRYSIDEID, sourceStrArray[i]);
                } else if (i == 1) {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.AFFAIRSID, sourceStrArray[i]);
                } else if (i == 2) {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.SPECIALID, sourceStrArray[i]);
                }
            }
        }
    }

    /**
     * 解析广告开关
     *
     * @param str
     */
    private void analysisAdv(String str) {
        if (StringUtils.isNotEmpty(str)) {
            int maxSplit = 4;
            String[] sourceStrArray = str.split(",", maxSplit);
            if (sourceStrArray.length == 1) {
                if (sourceStrArray[0].equals("0")) {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.LIST_ADV, "0");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.OTHER_ADV, "0");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.COUPONADV, "0");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.HOMEADV, "0");
                } else {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.LIST_ADV, "1");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.OTHER_ADV, "1");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.COUPONADV, "1");
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.HOMEADV, "1");
                }
            } else {
                for (int i = 0; i < sourceStrArray.length; i++) {
                    if (i == 0) {
                        CommonUtils.getInstance().putConfigData(AppConfigConstant.HOMEADV, sourceStrArray[i]);
                    } else if (i == 1) {
                        CommonUtils.getInstance().putConfigData(AppConfigConstant.LIST_ADV, sourceStrArray[i]);
                    } else if (i == 2) {
                        CommonUtils.getInstance().putConfigData(AppConfigConstant.COUPONADV, sourceStrArray[i]);
                    } else {
                        CommonUtils.getInstance().putConfigData(AppConfigConstant.OTHER_ADV, sourceStrArray[i]);
                    }
                }
            }

        } else {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.LIST_ADV, "0");
            CommonUtils.getInstance().putConfigData(AppConfigConstant.OTHER_ADV, "0");
            CommonUtils.getInstance().putConfigData(AppConfigConstant.COUPONADV, "0");
            CommonUtils.getInstance().putConfigData(AppConfigConstant.HOMEADV, "0");
        }

    }

    /**
     * 解析出新闻样式
     *
     * @param str
     */
    private void analysisStyle(String str) {
        List<NewsStyleBean> styleBeanList = new ArrayList<>();
        if (StringUtils.isNotEmpty(str)) {//----------------------------------0,3,7&1,2#2,3#1,1
            try {
                String posStr = str.substring(0, str.indexOf("&"));//-------------0,3,7
                String styleStr = str.substring(str.indexOf("&") + 1);//----------1,2#2,3#1,1
                String[] posAry = posStr.split(",");//----------------------------{"0","3","7"}
                CommonUtils.getInstance().putConfigData(AppConfigConstant.GLOBAL_STYLE, false);
                for (String aPosAry : posAry) {
                    if ("0".equalsIgnoreCase(aPosAry)) {
                        CommonUtils.getInstance().putConfigData(AppConfigConstant.GLOBAL_STYLE, true);
                    }
                }
                String[] styleAry = styleStr.split("#");//------------------------{"1,2","2,3","1,1"}
                for (int i = 0; i < posAry.length; i++) {
                    String[] newStyle = styleAry[i].split(",");//-----------------{"1","2"}
                    NewsStyleBean bean = new NewsStyleBean(Integer.parseInt(posAry[i]), Integer.parseInt(newStyle[0]), Integer.parseInt(newStyle[1]));
                    styleBeanList.add(bean);
                }
                CommonUtils.getInstance().putConfigData(AppConfigConstant.STYLE_BEAN_LIST, styleBeanList);
                Hawk.put("style", styleBeanList);
            } catch (Exception e) {
                if (Hawk.contains("style")) {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.STYLE_BEAN_LIST, Hawk.get("style"));
                }
            }
        } else {
            if (Hawk.contains("style")) {
                CommonUtils.getInstance().putConfigData(AppConfigConstant.STYLE_BEAN_LIST, Hawk.get("style"));
            }
        }

        boolean globalStyle = CommonUtils.getInstance().getGlobalStyle();
        if (globalStyle) {
            List<NewsStyleBean> sBeanList = CommonUtils.getInstance().getGlobalStyleBeanList();
            for (int i = 0; i < sBeanList.size(); i++) {
                if (sBeanList.get(i).getPosition() == 0) {
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.GLOBAL_COMMON, sBeanList.get(i).getCommonStyle());
                    CommonUtils.getInstance().putConfigData(AppConfigConstant.GLOBAL_VIDEO, sBeanList.get(i).getVideoStyle());
                }
            }
        } else {
            CommonUtils.getInstance().putConfigData(AppConfigConstant.GLOBAL_COMMON, 0);
            CommonUtils.getInstance().putConfigData(AppConfigConstant.GLOBAL_VIDEO, 0);
        }

    }


}
